#include "data.hpp"
#include "base.hpp"
#include "diff.hpp"
#include <assert.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <sstream>
#include <vector>

const char *SEPERATOR = "\n"; // 这里跟git的实现有些许不同，这里的分隔符是空格，而git的分隔符是\0
                              // 便于调试

// 这里的所有的路径都是绝对路径了

ErrorMessage InitCommand::handle_command() {

    if (check_file_exist(GIT_DIR, true)) {
        return ErrorMessage(ERROR_FILE_EXISTS, GIT_DIR);
    }

    // 创建目标文件夹
    std::filesystem::create_directory(GIT_DIR);
    std::filesystem::create_directory(OBJECT_DIR);
    std::filesystem::create_directory(REFS_DIR);
    std::filesystem::create_directory(TAGS_DIR);
    std::filesystem::create_directory(HEADS_DIR);

    // 设置初始化的branch为master
    this->set_ref_oid("master", DEFAULT_PARENT_OID);
    this->set_head("ref:master");
    return ErrorMessage();
}

ErrorMessage HashObjectCommand::handle_command() {
    assert(options.size() >= 1);
    return convert_files_to_blob(options.begin()->second);
}

ErrorMessage CatFileCommand::handle_command() {
    assert(options.size() >= 1);
    return convert_blob_to_stream(options.begin()->second, std::cout);
}

ErrorMessage WriteTreeCommand::handle_command() {
    return convert_dir_to_tree(current_dir);
};

ErrorMessage ReadTreeCommand::handle_command() {
    assert(options.size() >= 1);
    delete_files_except(current_dir, {GIT_DIR, current_dir / PROJECT_NAME, current_dir / "/git"});
    return convert_tree_to_dir(options.begin()->second);
};

ErrorMessage CommitCommand::create_object_by_index() {
    // 通过index文件生成object文件
    std::vector<std::string> object_info;
    std::ifstream ifs(INDEX_FILE, std::ios::binary);
    if (!ifs.is_open()) {
        std::cerr << "无法打开文件 " << INDEX_FILE.string() << " 进行读取。" << std::endl;
        return ErrorMessage(ERROR_FAILED_TO_READ_FILE, INDEX_FILE.string());
    }

    while (true) {
        ObjectType type = get_file_type(ifs);
        if (type == ObjectType::INVAILD_OBJECT) {
            break;
        }
        ObjectFile object_file;
        switch (type) {
        case ObjectType::BLOB_OBJ: {
            ifs >> object_file;
            object_file.type = type;
            object_info.push_back(object_file.to_string());
        } break;
        default:
            break;
        }
    }

    ifs.close();
    // 创建tree对象
    ErrorMessage error_message = string_SHA1(object_info);
    return error_message;
};

ErrorMessage CommitCommand::handle_command() {
    assert(options.size() >= 1);
    ErrorMessage error_message = create_object_by_index();
    if (error_message.code != ERROR_OK) {
        return error_message;
    } else {
        // 复制index文件到.mgit目录
        try {
            // 复制文件
            std::filesystem::copy(INDEX_FILE, OBJECT_DIR / error_message.message,
                                  std::filesystem::copy_options::overwrite_existing);
            // std::cout << "File copied successfully!" << std::endl;
        } catch (const std::exception &e) {
            std::cerr << "Error: " << e.what() << std::endl;
        }

        // 删掉index文件
        std::filesystem::remove(INDEX_FILE);

        // 生成commitMessage信息
        CommitMessage commitMessage;
        commitMessage.branch_name    = get_head_ref();
        commitMessage.parent_oid_vct = this->get_head_oids();

        // 刚刚merge的时候，get_head_oids()会返回两个oid，这里需要设置head仅指向第一个
        if (commitMessage.parent_oid_vct.size() > 1) {
            this->set_head("ref:" + get_head_ref());
            return ErrorMessage(ERROR_OK, "");
        }

        if (commitMessage.parent_oid_vct.front() != DEFAULT_PARENT_OID) {
            std::ifstream ifs(OBJECT_DIR / commitMessage.parent_oid_vct.front(), std::ios::binary);
            if (!ifs.is_open()) {
                std::cerr << "无法打开文件 " << commitMessage.parent_oid_vct.front()
                          << " 进行读取。" << std::endl;
                return ErrorMessage(ERROR_FAILED_TO_READ_FILE,
                                    commitMessage.parent_oid_vct.front());
            } else {
                CommitMessage parentCommitMessage;
                ifs >> parentCommitMessage;

                ifs.close();
                if (parentCommitMessage.obj_oid == error_message.message) {
                    std::cerr << "当前目录没有修改，无需commit" << std::endl;
                    return ErrorMessage(ERROR_OK, "");
                }
            }
        }
        commitMessage.obj_oid = error_message.message;
        // 获取当前时间
        auto now = std::chrono::system_clock::now();
        // 转换为系统时间
        std::time_t time                = std::chrono::system_clock::to_time_t(now);
        commitMessage.commit_local_time = *std::localtime(&time);
        commitMessage.message           = options.begin()->second;
        std::vector<std::string> strs   = {commitMessage.to_string()};
        commitMessage.add_message_oid   = string_SHA1(strs).message;
        // 创建以add_message_oid为名的文件，写入commit message
        {
            std::ofstream commit_file(OBJECT_DIR / commitMessage.add_message_oid);
            if (commit_file.is_open()) {
                commit_file << commitMessage.to_string();
                commit_file.close();
            } else {
                // 处理文件打开失败的情况
                std::cerr << "无法创建或打开文件: " << commitMessage.add_message_oid << std::endl;
                return ErrorMessage(ERROR_FILE_WRITE_FAILED, commitMessage.add_message_oid);
            }
        }
        std::string head_ref = get_head_ref();
        if (head_ref == "") {
            this->set_head(commitMessage.add_message_oid);
        } else {
            this->set_ref_oid(head_ref, commitMessage.add_message_oid);
        }

        // std::cout << commitMessage.to_string() << std::endl;
    }

    return error_message;
};

void Command::set_head(std::string strs) {

    // 打开文件以进行写入操作，ios::out 表示写入
    std::ofstream outFile(HEAD, std::ios::out);
    // 检查文件是否成功打开
    if (!outFile.is_open()) {
        std::cerr << "无法打开文件 " << HEAD.string() << " 进行写入。" << std::endl;
        return;
    }

    // 写入内容
    outFile << strs << std::endl;
    // 关闭文件
    outFile.close();
};

void Command::append_head(std::string strs) {
    // 打开文件以进行追加操作，ios::app 表示追加
    std::ofstream outFile(HEAD, std::ios::app);
    // 检查文件是否成功打开
    if (!outFile.is_open()) {
        std::cerr << "无法打开文件 " << HEAD.string() << " 进行追加。" << std::endl;
        return;
    }

    // 写入内容
    outFile << strs << std::endl;
    // 关闭文件
    outFile.close();
};

void Command::set_ref_oid(std::string refName, std::string oid) {
    std::ofstream outFile(HEADS_DIR / refName, std::ios::out);
    if (!outFile.is_open()) {
        std::cerr << "无法打开文件 " << REFS_DIR / refName << " 进行写入。" << std::endl;
        return;
    }
    outFile << oid << std::endl;
    outFile.close();
};
std::string Command::get_head_ref() {
    if (check_file_exist(HEAD, false) == false) {
        std::cout << "起始文件，无parent" << std::endl;
        return "";
    }

    std::ifstream inFile(HEAD, std::ios::in);
    // 检查文件是否成功打开
    if (!inFile.is_open()) {
        std::cerr << "无法打开文件 " << HEAD.string() << " 进行读取。" << std::endl;
        exit(1);
    }
    std::string head_oid;
    inFile >> head_oid;
    inFile.close();
    if (head_oid.find("ref:") != std::string::npos) {
        return head_oid.substr(4);
    } else {
        return "";
    }
};

std::vector<std::string> Command::get_head_oids() {
    // 打开文件以进行读取操作，ios::in 表示读取
    if (check_file_exist(HEAD, false) == false) {
        // std::cout << "起始文件，无parent" << std::endl;
        return {DEFAULT_PARENT_OID};
    }

    std::ifstream inFile(HEAD, std::ios::in);
    // 检查文件是否成功打开
    if (!inFile.is_open()) {
        std::cerr << "无法打开文件 " << HEAD.string() << " 进行读取。" << std::endl;
        exit(1);
    }
    // 读取第一个单词，判断是否有parent
    std::vector<std::string> head_oids;
    std::string head_oid;
    while (std::getline(inFile, head_oid)) {
        if (head_oid.find("ref:") != std::string::npos && head_oid.size() > 5) {
            std::string ref_name = head_oid.substr(4);
            head_oid             = get_ref_oid(ref_name);
            head_oids.push_back(head_oid);
        } else {
            head_oids.push_back(head_oid);
            break;
        }
    };

    return head_oids;
};

std::string Command::get_ref_oid(std::string refName) {
    std::ifstream inFile(HEADS_DIR / refName, std::ios::in);
    if (!inFile.is_open()) {
        std::cerr << "无法打开文件 " << HEADS_DIR / refName << " 进行读取。" << std::endl;
        return "";
    }
    std::string ref_oid;
    inFile >> ref_oid;
    inFile.close();
    return ref_oid;
};

CommitMessage get_commit_message(std::string commitOid) {
    std::ifstream inFile(OBJECT_DIR / commitOid, std::ios::in);
    if (!inFile.is_open()) {
        std::cerr << "无法打开文件 " << commitOid << " 进行读取。" << std::endl;
        exit(1);
    }
    CommitMessage commit_message;
    inFile >> commit_message;
    inFile.close();
    return commit_message;
}
ErrorMessage LogCommand::handle_command() {
    std::string head_oid;
    if (this->options.size() == 0) {
        head_oid = this->get_head_oids().front();
        if (head_oid == DEFAULT_PARENT_OID) {
            std::cout << "无commit记录" << std::endl;
            return ErrorMessage(ERROR_OK, "");
        }
    } else {
        std::string tag_name = this->options["tag-name"];
        head_oid             = get_tag_oid(tag_name);
        if (head_oid == "") {
            std::cerr << "无法找到tag：" << tag_name << std::endl;
            return ErrorMessage(ERROR_INVALID_OBJECT_ID, tag_name);
        }
    }

    return this->print_log_message(head_oid);
};

ErrorMessage LogCommand::print_log_message(std::string head_oid) {
    std::ifstream ifs;
    while (true) {
        CommitMessage commitMessage = get_commit_message(head_oid);
        std::cout << commitMessage.to_string() << std::endl;
        if (commitMessage.parent_oid_vct.front() == DEFAULT_PARENT_OID ||
            commitMessage.parent_oid_vct.front() == "") {
            break;
        } else {
            head_oid = commitMessage.parent_oid_vct.front();
        }
    }
    return ErrorMessage(ERROR_OK, "");
};

ErrorMessage Command::get_commit_obj_oid(std::string commitOid) {
    if (check_file_exist(OBJECT_DIR / commitOid, false) == false) {
        std::cerr << "无法找到commit对象：" << commitOid << std::endl;
        return ErrorMessage(ERROR_INVALID_OBJECT_ID, commitOid);
    }
    std::ifstream ifs(OBJECT_DIR / commitOid, std::ios::binary);
    if (!ifs.is_open()) {
        std::cerr << "无法打开文件 " << commitOid << " 进行读取。" << std::endl;
        return ErrorMessage(ERROR_FAILED_TO_READ_FILE, commitOid);
    }
    CommitMessage commitMessage;
    ifs >> commitMessage;
    ifs.close();
    return ErrorMessage(ERROR_OK, commitMessage.obj_oid);
};

ErrorMessage CheckoutCommand::handle_command() {
    assert(options.size() >= 1);
    if (this->checkout_type == CheckoutType::CKECKOUT_OID) {
        return this->checkout_by_oid(options.begin()->second);
    } else if (this->checkout_type == CheckoutType::CKECKOUT_TAG) {
        return this->checkout_by_tag(options.begin()->second);
    } else if (this->checkout_type == CheckoutType::CKECKOUT_BRANCH) {
        return this->checkout_by_branch(options.begin()->second);
    } else {
        std::cerr << "checkout type error" << std::endl;
        exit(1);
    }
};

ErrorMessage CheckoutCommand::checkout_by_oid(std::string new_oid) {
    std::string head_oid = this->get_head_oids().front();
    if (head_oid == new_oid) {
        std::cout << "当前版本已经是最新版本" << std::endl;
        return ErrorMessage(ERROR_OK, "");
    } else {
        // 读取head文件，获取oid
        ErrorMessage error_message = this->get_commit_obj_oid(new_oid);
        if (error_message.code != ERROR_OK) {
            return error_message;
        } else {
            this->set_head(new_oid);
            delete_files_except(current_dir,
                                {GIT_DIR, current_dir / PROJECT_NAME, current_dir / "/git"});
            std::string start_oid_path = (OBJECT_DIR / error_message.message).string();
            return convert_tree_to_dir(start_oid_path);
        }
    }
};
ErrorMessage CheckoutCommand::checkout_by_tag(std::string tag_name) {
    std::string tag_oid = get_tag_oid(tag_name);
    if (tag_oid == "") {
        std::cerr << "无法找到tag：" << tag_name << std::endl;
        return ErrorMessage(ERROR_INVALID_OBJECT_ID, tag_name);
    }
    return this->checkout_by_oid(tag_oid);
};
ErrorMessage CheckoutCommand::checkout_by_branch(std::string branch_name) {
    std::string branch_oid = this->get_ref_oid(branch_name);
    if (branch_oid == "") {
        std::cerr << "无法找到分支：" << branch_name << std::endl;
        return ErrorMessage(ERROR_INVALID_BRANCH_NAME, branch_name);
    }
    ErrorMessage error_message = this->checkout_by_oid(branch_oid);
    if (error_message.code != ERROR_OK) {
        return error_message;
    } else {
        this->set_head("ref:" + branch_name);
        return ErrorMessage(ERROR_OK, "");
    }
};

ErrorMessage TagCommand::handle_command() {
    assert(this->options.size() >= 2);
    std::string tag_name = this->options["tag-name"];
    std::string tag_oid  = this->options["tag-oid"];
    if (!check_file_exist(OBJECT_DIR / tag_oid, false)) {
        std::cerr << "无法找到oid：" << tag_oid << std::endl;
        return ErrorMessage(ERROR_INVALID_OBJECT_ID, tag_oid);
    }
    std::ofstream ofs(TAGS_DIR / tag_name, std::ios::out);
    if (!ofs.is_open()) {
        std::cerr << "无法打开文件 " << TAGS_DIR / tag_name << " 进行写入。" << std::endl;
        return ErrorMessage(ERROR_FILE_WRITE_FAILED, TAGS_DIR / tag_name);
    }
    ofs << tag_oid << std::endl;
    ofs.close();
    return ErrorMessage(ERROR_OK, "");
};

ErrorMessage BranchCommand::handle_command() {

    switch (this->branch_type) {
    case BRANCH_CREATE:
        return this->create_branch(this->options["branch-name"]);
    case BRANCH_LIST:
        return this->list_branch();
    default:
        break;
    }
    return ErrorMessage(ERROR_INVALID_COMMAND_TYPE, "branch command type error");
}

ErrorMessage BranchCommand::create_branch(std::string branch_name) {
    std::string old_branch_oid = this->get_head_oids().front();
    this->set_ref_oid(branch_name, old_branch_oid);
    this->set_head("ref:" + branch_name);
    return ErrorMessage(ERROR_OK, "");
}

namespace fs = std::filesystem;
ErrorMessage BranchCommand::list_branch() {
    std::string now_branch_name = this->get_head_ref();
    std::cout << "all branch :\n";
    try {
        // 遍历目录中的每个条目
        for (const auto &entry : fs::directory_iterator(HEADS_DIR)) {
            // 判断是否是常规文件
            if (fs::is_regular_file(entry.status())) {
                // 打印文件名（不带路径）
                std::string branch_name = entry.path().filename().string();
                if (branch_name == now_branch_name) {
                    std::cout << "* ";
                } else {
                    std::cout << "  ";
                }
                std::cout << branch_name << "\t";
            }
            std::cout << std::endl;
        }
    } catch (const fs::filesystem_error &ex) {
        std::cerr << "Filesystem error: " << ex.what() << std::endl;
        return ErrorMessage(ERROR_FILE_NOT_FOUND, HEADS_DIR.string());
    }
    return ErrorMessage(ERROR_OK, "");
}
ErrorMessage StatusCommand::handle_command() {
    std::ifstream ifs(HEAD, std::ios::binary);
    std::map<std::string, DiffFile> file_map;
    CommitMessage commitMessage;
    if (!ifs.is_open()) {
        std::cerr << "无法打开文件 " << HEAD.string() << " 进行读取。" << std::endl;
        return ErrorMessage(ERROR_FAILED_TO_READ_FILE, HEAD.string());
    } else {
        std::string branch_name;
        ifs >> branch_name;
        ifs.close();
        if (branch_name.find("ref:") != std::string::npos) {
            branch_name = branch_name.substr(4);
        }
        std::cout << "now_branch: " << branch_name << std::endl;

        commitMessage = get_commit_message(this->get_head_oids().front());
        file_map      = diff_current_tree(commitMessage.obj_oid);
        for (auto &diff_file : file_map) {
            if (diff_file.second.diff_type != DiffType::DIFF_TYPE_SAME) {
                std::cout << "  " << diff_file.second.to_string() << std::endl;
            }
        }
    }
    // 展示暂存区
    std::cout << "staged files:" << std::endl;
    std::map<std::string, DiffFile> staged_file_map = diff_staged_tree(commitMessage.obj_oid);
    for (auto &diff_file : staged_file_map) {
        if (diff_file.second.diff_type != DiffType::DIFF_TYPE_SAME) {
            std::cout << "  " << diff_file.second.to_string() << std::endl;
        }
    }
    return ErrorMessage(ERROR_OK, "");
}

ErrorMessage ResetCommand::handle_command() {
    assert(options.size() >= 1);
    std::string reset_oid = options.begin()->second;
    if (!check_file_exist(OBJECT_DIR / reset_oid, false)) {
        std::cerr << "无法找到oid：" << reset_oid << std::endl;
        return ErrorMessage(ERROR_INVALID_OBJECT_ID, reset_oid);
    }
    std::string now_branch_name = this->get_head_ref();
    std::string head_oid        = this->get_ref_oid(now_branch_name);
    if (head_oid == reset_oid) {
        std::cout << "当前版本已经是最新版本" << std::endl;
        return ErrorMessage(ERROR_OK, "");
    } else {
        // 读取head文件，获取oid
        ErrorMessage error_message = this->get_commit_obj_oid(reset_oid);
        if (error_message.code != ERROR_OK) {
            return error_message;
        } else {
            this->set_ref_oid(now_branch_name, reset_oid);
            delete_files_except(current_dir,
                                {GIT_DIR, current_dir / PROJECT_NAME, current_dir / "/git"});
            std::string start_oid_path = (OBJECT_DIR / error_message.message).string();
            return convert_tree_to_dir(start_oid_path);
        }
    }
}

ErrorMessage ShowCommand::handle_command() {
    CommitMessage commitMessage = get_commit_message(this->get_head_oids().front());
    std::cout << commitMessage.to_string() << std::endl;
    CommitMessage parentMessage = get_commit_message(commitMessage.parent_oid_vct.front());
    if (parentMessage.parent_oid_vct.front() == DEFAULT_PARENT_OID) {
        return ErrorMessage(ERROR_OK, "");
    } else {
        std::map<std::string, DiffFile> file_map =
            diff_trees(commitMessage.obj_oid, parentMessage.obj_oid);
        for (auto &diff_file : file_map) {
            if (diff_file.second.diff_type != DiffType::DIFF_TYPE_SAME) {
                std::cout << diff_file.second.to_string() << std::endl;
                if (diff_file.second.diff_type == DiffType::DIFF_TYPE_MODIFY) {
                    std::cout << diff_files(OBJECT_DIR / diff_file.second.elem_one_oid,
                                            OBJECT_DIR / diff_file.second.elem_two_oid,
                                            diff_file.second.file_name, diff_file.second.file_name)
                              << std::endl;
                }
            }
        }
    }
    return ErrorMessage(ERROR_OK, "");
};

ErrorMessage DiffCommand::handle_command() {
    std::string head_oid = this->get_head_oids().front();
    if (head_oid == DEFAULT_PARENT_OID) {
        std::cout << "无commit记录" << std::endl;
        return ErrorMessage(ERROR_OK, "");
    } else {
        CommitMessage commitMessage = get_commit_message(head_oid);
        std::map<std::string, DiffFile> file_map;
        if (diff_type == DiffTypeCommand::DIFF_HEAD) {
            file_map = diff_current_tree(commitMessage.obj_oid);
        } else if (diff_type == DiffTypeCommand::DIFF_STAGED) {
            file_map = diff_staged_tree(commitMessage.obj_oid);
        }

        for (auto &diff_file : file_map) {
            if (diff_file.second.diff_type != DiffType::DIFF_TYPE_SAME) {
                std::cout << diff_file.second.to_string() << std::endl;
                if (diff_file.second.diff_type == DiffType::DIFF_TYPE_MODIFY) {
                    std::cout << diff_current_files(diff_file.second.file_name,
                                                    OBJECT_DIR / diff_file.second.elem_two_oid,
                                                    diff_file.second.file_name,
                                                    diff_file.second.file_name)
                              << std::endl;
                }
            }
        }
    }
    return ErrorMessage(ERROR_OK, "");
}

ErrorMessage MergeCommand::handle_command() {
    // 先只支持merge两个branch
    assert(options.size() >= 1);
    std::string merge_branch_name = options.begin()->second;
    std::string merge_branch_oid  = this->get_ref_oid(merge_branch_name);
    if (merge_branch_oid == "") {
        std::cerr << "无法找到分支：" << merge_branch_name << std::endl;
        return ErrorMessage(ERROR_INVALID_BRANCH_NAME, merge_branch_name);
    }
    if (merge_branch_name == this->get_head_ref()) {
        std::cout << "当前分支已经是" << merge_branch_name << "分支" << std::endl;
        return ErrorMessage(ERROR_OK, "");
    }
    // 假设当前已经commit了
    CommitMessage commitMessageOne = get_commit_message(this->get_head_oids().front());
    CommitMessage commitMessageTwo = get_commit_message(this->get_ref_oid(merge_branch_name));

    // 判断是否是fast-forward模式
    std::set<std::string> ans_set = get_commit_ancestors(commitMessageTwo.add_message_oid);
    if (ans_set.count(commitMessageOne.add_message_oid) > 0) {
        // 移动head指针
        this->set_ref_oid(this->get_head_ref(), merge_branch_oid);
        // 恢复文件
        delete_files_except(current_dir,
                            {GIT_DIR, current_dir / PROJECT_NAME, current_dir / "/git"});
        std::string start_oid_path = (OBJECT_DIR / commitMessageTwo.obj_oid).string();
        return convert_tree_to_dir(start_oid_path);
    }

    // 正常合并
    auto file_map = diff_trees(commitMessageOne.obj_oid, commitMessageTwo.obj_oid);
    std::string parent_commit_oid =
        get_common_ancestor(commitMessageOne.add_message_oid, commitMessageTwo.add_message_oid);

    diff_build_parent_oid(file_map, get_commit_message(parent_commit_oid).obj_oid);
    merge_two_commit(file_map);

    // 将新的branch写入head文件
    this->append_head("ref:" + merge_branch_name);
    return ErrorMessage(ERROR_OK, "");
}

ErrorMessage MergeBaseCommand::handle_command() {
    assert(options.size() >= 2);
    std::string branch_name_one = options["branch-name-one"];
    std::string branch_name_two = options["branch-name-two"];
    std::string branch_oid_one  = this->get_ref_oid(branch_name_one);
    std::string branch_oid_two  = this->get_ref_oid(branch_name_two);
    if (branch_oid_one == "" || branch_oid_two == "") {
        std::cerr << "无法找到分支：" << branch_name_one << " 或 " << branch_name_two << std::endl;
        return ErrorMessage(ERROR_INVALID_BRANCH_NAME, branch_name_one + " 或 " + branch_name_two);
    }
    std::cout << get_common_ancestor(branch_oid_one, branch_oid_two) << std::endl;
    return ErrorMessage(ERROR_OK, "");
}

ErrorMessage AddCommand::handle_command() {
    assert(options.size() >= 1);
    // 获取原来add的文件map
    auto index_map = get_object_list(INDEX_FILE);
    // 获取要add的文件列表
    auto add_files = convert_object_list(current_dir / this->options["file-name"]);
    for (auto &file_path : add_files) {
        if (index_map.count(file_path.file_name) != 0) {
            // 删除旧的索引文件
            std::filesystem::remove(OBJECT_DIR / index_map[file_path.file_name].oid);
        }
        // 写入索引文件
        index_map[file_path.file_name] = file_path;
    }

    // 写入索引文件
    std::ofstream ifs(INDEX_FILE, std::ios::binary);
    if (!ifs.is_open()) {
        std::cerr << "无法打开文件 " << INDEX_FILE.string() << " 进行写入。" << std::endl;
        return ErrorMessage(ERROR_FILE_WRITE_FAILED, INDEX_FILE.string());
    }
    for (auto &index_file : index_map) {
        ifs << index_file.second.to_string();
    }
    ifs.close();
    return ErrorMessage(ERROR_OK, "");
}